/**
 * @author hanzc (hanzhichen@baijia.com)
 * @date 2021-01-20
 * fineBi经分概览看板part1: 收入看板
 */
import React, {useState, useEffect} from 'react';
import {useMount} from 'ahooks';
import moment from 'moment';
import {Row, Col, Card, Typography, Input} from 'antd';
import {
    querySelectOptions,
    queryPart1Values,
    queryDetailInPart1,
    downloadInPart1
} from '~/service/generalView';
import CommonSearchBar from '../../../common/CommonSearchBar';
import DetailCard from '../../../common/DetailCard';
import DetailModal from '../../../common/DetailModal';
import Loading from '../../../common/Loading';
import {searchFormPart1, pageId} from '../../config';
import IncomeDetailCardTable from '../../../common/DetailCardTable';
import {formatRangePickerValue} from '../../../utils/convert';
import IncomeStructurePieChart from './IncomeStructurePieChart';
import IncomeBarChart from './IncomeBarChart';

const {TextArea} = Input;
const {Title} = Typography;

const handleNegativePieSeries = (pieSeries = []) => {
    const newSeries = pieSeries.map(seriesItem => {
        if (seriesItem?.type && seriesItem.type !== 'pie') {
            return seriesItem;
        }
        const {data: seriesItemData = [], ...rest} = seriesItem;
        const newData = seriesItemData.map(dataItem => {
            const {value = '', ...rest1} = dataItem;
            return {
                ...rest1,
                value: Math.abs(parseFloat(value)),
                originValue: value
            };
        });
        return {...rest, data: newData};
    });
    return newSeries;
};

const formatDateSearchValue = formatRangePickerValue('YYYY-MM-DD');

/** 经分概览看板part1: 收入看板 */
const IncomeDashBoard = props => {
    // 收入看板控制originPaidDay, 所以外部只提供初始值
    const {initOriginPaidDay, onOriginPaidDayChange} = props;
    const initialValues = {originPaidDay: initOriginPaidDay};

    const [loading, setLoading] = useState(false);
    const [loading1, setLoading1] = useState(false);
    const [result, setResult] = useState({});
    // searchform
    // searchform中的select, 数据源全部都是动态从后端查询的
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    // drilling
    const [drilingList, setDrilingList] = useState([]);
    const [drilingLevel, setDrilingLevel] = useState(null);
    // detail
    const [detailData, setDetailData] = useState({});
    const [detailModalVisible, setDetailModalVisible] = useState(false);

    // 返回结果是这样的格式, title是标题; 1-4是数据卡片; 5是echarts的数据源, 两个chart的数据源都在5里面.
    const {
        generalViewTitle = {},
        generalViewPartOne = {},
        generalViewPartTwo = {},
        generalViewPartThree = {},
        generalViewPartFour = {},
        generalViewPartFive = {},
        generalViewPartOne_1: generalViewPartSeven = {},
        generalViewPartOne_2: generalViewPartEight = {}
    } = result;
    const {
        money: [money1 = {}] = [],
        moneyByDepartment: [moneyByDepartment1 = {}] = []
    } = generalViewPartOne;
    const {
        money: [money2 = {}] = [],
        moneyByDepartment: [moneyByDepartment2 = {}] = []
    } = generalViewPartTwo;
    const {
        money: [money3 = {}] = [],
        moneyByDepartment: [moneyByDepartment3 = {}] = []
    } = generalViewPartThree;
    const {
        money: [money4 = {}] = [],
        moneyByDepartment: [moneyByDepartment4 = {}] = []
    } = generalViewPartFour;

    const {
        money: [money7 = {}] = [],
        moneyByDepartment: [moneyByDepartment7 = {}] = []
    } = generalViewPartSeven;

    const {
        money: [money8 = {}] = [],
        moneyByDepartment: [moneyByDepartment8 = {}] = []
    } = generalViewPartEight;

    const {textList = []} = generalViewTitle;
    const titleTextContent = textList[0]?.textContent ?? '';
    const {pieUnit = [], compositeUnit = []} = generalViewPartFive;
    const pieChartUnit = pieUnit[0] ?? {};
    const comChartUnit = compositeUnit[0] ?? {};

    // pieUnit有负值, 提前处理下
    // 重新设置series
    if (pieChartUnit?.chart?.series) {
        pieChartUnit.chart.series = handleNegativePieSeries(
            pieChartUnit?.chart?.series ?? []
        );
    }

    /** 查询方法 */
    const getData = params => {
        const {loadingFn = setLoading} = params;

        loadingFn(true);

        const {originPaidDay, ...rest} = params || {};
        let newQueryParams = params;
        if (originPaidDay == null) {
            newQueryParams = rest;
        } else {
            const formattedOriginPaidDay = formatDateSearchValue(originPaidDay);
            newQueryParams = {originPaidDay: formattedOriginPaidDay, ...rest};
        }
        queryPart1Values(newQueryParams)
            .then(res => {
                const {data = {}} = res;
                setResult(data);
            })
            .finally(() => {
                loadingFn(false);
            });
    };

    /** 点击搜索按钮 */
    const handleSearch = params => {
        setSearchFormValues(params);
        const {originPaidDay} = params || {};
        // 搜索时设置下面组件的支付时间
        onOriginPaidDayChange(originPaidDay);
        setDrilingLevel(null);
        setDrilingList([]);
        getData(params);
    };

    const handleReset = () => {
        setSearchFormValues(initialValues);
        // 重置时设置下面组件的支付时间
        onOriginPaidDayChange(initOriginPaidDay);
        setDrilingLevel(null);
        setDrilingList([]);
        getData(initialValues);
    };
    // detail
    // 函数柯里化, 提前记录unit参数
    const handleDetail = ({unitId = '', unitName = ''}) => () => {
        console.log(unitId, unitName, 'unit');
        setDetailModalVisible(true);
        const {originPaidDay, ...rest} = searchFormValues || {};
        let formattedSearchFormValues = searchFormValues;
        if (originPaidDay == null) {
            formattedSearchFormValues = rest;
        } else {
            const formattedOriginPaidDay = formatDateSearchValue(originPaidDay);
            formattedSearchFormValues = {
                originPaidDay: formattedOriginPaidDay,
                ...rest
            };
        }
        const params = {
            ...formattedSearchFormValues,
            unitId,
            unitName,
            drilingList
        };
        queryDetailInPart1(params).then(res => {
            const {data} = res;
            setDetailData(data);
        });
    };
    const handleDownload = ({unitId = '', unitName = ''}) => () => {
        const {originPaidDay, ...rest} = searchFormValues || {};
        let formattedSearchFormValues = searchFormValues;
        if (originPaidDay == null) {
            formattedSearchFormValues = rest;
        } else {
            const formattedOriginPaidDay = formatDateSearchValue(originPaidDay);
            formattedSearchFormValues = {
                originPaidDay: formattedOriginPaidDay,
                ...rest
            };
        }
        const params = {
            ...formattedSearchFormValues,
            unitId,
            unitName,
            drilingList
        };
        const excelName = unitName ? unitName : null;
        downloadInPart1({params, excelName});
    };
    const handleBack = ({unitId = ''}) => async params => {
        // 所有下钻取消
        setDrilingList([]);
        try {
            await getData({...searchFormValues, loadingFn: setLoading1});
            // 返回搜索数据接口调用成功后level - 1
            setDrilingLevel({unitId, level: 0});
        } catch {}
    };
    // drilling, 下钻, 会重新加载模块
    const handleDrilling = (chartUnit = {}) => async params => {
        const {info} = params;
        const {unitId = '', unitName = '', config = {}} = chartUnit;
        const {dimensionList = []} = config;
        const [firstDimension] = dimensionList;
        const {dimensionId = '', dimensionName = ''} = firstDimension || {};
        const driling = {
            unitId,
            unitName,
            value: info?.name,
            dimensionId,
            dimensionName
        };
        setDrilingList([driling]);
        try {
            await getData({...searchFormValues, drilingList: [driling], loadingFn: setLoading1});
            // 搜索接口调用成功后level + 1, 现在是0就是没下钻, 1就是有下钻, 多级下钻也是1.
            setDrilingLevel({unitId, level: 1});
        } catch {}
    };
    // 请求单个表单配置项
    const handleFetchOptions = ({
        key,
        searchKey,
        pager,
        dependItemKey,
        dependItemValue,
        isGetingMore,
        options: curOptions,
        fieldsValue
    }) => {
        let permissions = searchFormPart1.map(item => {
            if (item.key === 'originPaidDay') {
                const [begin, end] = fieldsValue[item.key] || [];
                const filterItems = (begin || end) && [
                    begin && moment(begin).format('YYYY-MM-DD'),
                    end && moment(end).format('YYYY-MM-DD')
                ];
                return {
                    dimensionId: item.key,
                    dimensionName: item.key,
                    filterItems
                };
            }
            return {
                dimensionId: item.key,
                dimensionName: item.key,
                filterItems: fieldsValue[item.key]
            };
        });

        permissions = permissions.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: key,
            dimensionName: key,
            searchKey,
            permissions,
            unitId: pageId.part1.selectID
        };

        querySelectOptions(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };

    // mount
    useMount(() => {
        getData(initialValues);
    }, []);

    return (
        <div style={{marginTop: 24}}>
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    config={searchFormPart1}
                    selectOptions={selectOptions}
                    initialValues={initialValues}
                    noCache
                    onOk={handleSearch}
                    onReset={handleReset}
                    onfetchOptions={handleFetchOptions}
                    loading={loading}
                />
            </Card>
            <Card>
                <div style={{marginBottom: 8}}>
                    <Loading loading={loading}>
                        <TextArea
                            value={titleTextContent || ''}
                            readOnly
                            bordered={false}
                            className="general-text-area"
                            style={{height: 108}}
                        />
                    </Loading>
                </div>
                <Row>
                    <Col span={8}>
                        <DetailCard
                            title={money1?.unitName ?? ''}
                            onDownload={handleDownload(moneyByDepartment1)}
                            onDetail={handleDetail(moneyByDepartment1)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <IncomeDetailCardTable
                                    dataSource={generalViewPartOne}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={8}>
                        <DetailCard
                            title={money3?.unitName ?? ''}
                            onDownload={handleDownload(moneyByDepartment3)}
                            onDetail={handleDetail(moneyByDepartment3)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <IncomeDetailCardTable
                                    dataSource={generalViewPartThree}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={8}>
                        <DetailCard
                            title={money7?.unitName ?? ''}
                            onDownload={handleDownload(moneyByDepartment7)}
                            onDetail={handleDetail(moneyByDepartment7)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <IncomeDetailCardTable
                                    dataSource={generalViewPartSeven}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={8}>
                        <DetailCard
                            title={money2?.unitName ?? ''}
                            onDownload={handleDownload(moneyByDepartment2)}
                            onDetail={handleDetail(moneyByDepartment2)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <IncomeDetailCardTable
                                    dataSource={generalViewPartTwo}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={8}>
                        <DetailCard
                            title={money4?.unitName ?? ''}
                            onDownload={handleDownload(moneyByDepartment4)}
                            onDetail={handleDetail(moneyByDepartment4)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <IncomeDetailCardTable
                                    dataSource={generalViewPartFour}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={8}>
                        <DetailCard
                            title={money8?.unitName ?? ''}
                            onDownload={handleDownload(moneyByDepartment8)}
                            onDetail={handleDetail(moneyByDepartment8)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <IncomeDetailCardTable
                                    dataSource={generalViewPartEight}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <DetailCard
                            title={pieChartUnit?.unitName ?? ''}
                            onDownload={handleDownload(pieChartUnit)}
                            onDetail={handleDetail(pieChartUnit)}
                            onBack={handleBack(pieChartUnit)}
                            showBack={
                                drilingLevel &&
                                drilingLevel?.unitId === pieChartUnit?.unitId &&
                                drilingLevel?.level > 0
                            }
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading || loading1}>
                                <IncomeStructurePieChart
                                    dataSource={pieChartUnit}
                                    id="IncomeStructurePieChart"
                                    onDrilling={handleDrilling(pieChartUnit)}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={12}>
                        <DetailCard
                            title={comChartUnit?.unitName ?? ''}
                            onDownload={handleDownload(comChartUnit)}
                            onDetail={handleDetail(comChartUnit)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <IncomeBarChart
                                    dataSource={comChartUnit}
                                    id="IncomeBarChart"
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
            </Card>
            <DetailModal
                data={detailData}
                detailModalVisible={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
            />
        </div>
    );
};

export default IncomeDashBoard;
